package mess;

import java.util.List;

public class LeeCode_19 {
    public static void main(String[] args) {
      /*  ListNode l1 = new ListNode(1, new ListNode(2, new ListNode(3,new ListNode(4,new ListNode(5)))));
        System.out.println(removeNthFromEnd(l1, 2));*/
        ListNode l2 = new ListNode(1, new ListNode(2));
        System.out.println(removeNthFromEnd(l2, 2));
    }

    private static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode start = head;
        int len = 0;
        while (start != null){
            start = start.next;
            len++;
        }
        if (len == 1)
            return null;
        if (len == n)
            return head.next;
        int index = len - n;
        ListNode before = head;
        for (int i = 1; i < index; i++)
            before = before.next;
        System.out.println(before);
        ListNode after = before.next.next;
        System.out.println(after);
        before.next = after;
        return head;
    }

    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return this.val + "->" + this.next;
        }
    }
}
